package com.yeskery.nut.extend.mcp.server;

import com.yeskery.nut.core.*;
import com.yeskery.nut.http.SseEmitter;
import com.yeskery.nut.util.StringUtils;

import java.util.UUID;

/**
 * SSE MCP初始化请求处理器
 * @author sprout
 * 2025-04-17 10:50
 */
public class SseMcpServerInitializationRequestHandler implements RequestHandler {

    /** 环境对象 */
    private final Environment environment;

    /** message端点 */
    private final String messageEndpoint;

    /** Mcp会话管理器 */
    private final McpSessionManager mcpSessionManager;

    /**
     * 构建SSE MCP初始化请求处理器
     * @param environment 环境对象
     * @param messageEndpoint message端点
     * @param mcpSessionManager Mcp会话管理器
     */
    public SseMcpServerInitializationRequestHandler(Environment environment, String messageEndpoint, McpSessionManager mcpSessionManager) {
        this.environment = environment;
        this.messageEndpoint = messageEndpoint;
        this.mcpSessionManager = mcpSessionManager;
    }

    @Override
    public void handle(Request request, Response response, Execution execution) {
        SseEmitter sseEmitter = new SseEmitter();
        sseEmitter.setTimeout(getTimeout());
        String sessionId = UUID.randomUUID().toString();
        McpServerSession serverSession = new McpServerSession();
        serverSession.setSseEmitter(sseEmitter);
        mcpSessionManager.putClient(sessionId, serverSession);
        McpSseEmitterResponseBodyHandler sseResponseEmitterHandler = new McpSseEmitterResponseBodyHandler(messageEndpoint, sessionId);
        sseResponseEmitterHandler.handle(sseEmitter, request, response);
    }

    /**
     * 获取超时时间
     * @return 超时时间
     */
    private Long getTimeout() {
        String value = environment.getEnvProperty("nut.mcp.server.sse.timeout");
        return StringUtils.isEmpty(value) ? 0L : Long.parseLong(value);
    }
}
